import qs from "qs";
import axios, { AxiosResponse } from "axios";
import { BaseResponse } from "../type";
import { message } from "antd";
import { BASE_URL, TIME_OUT } from "../config/axios";
// import { useStorage } from "../untils/storeage";

const instance = axios.create({
  baseURL: BASE_URL,
  timeout: TIME_OUT,
});

instance.interceptors.request.use(
  (config) => {
    // const storage = useStorage(window.localStorage)
    // config.headers["Authorization"] =storage.get("login").token; // 请求头携带 token
    // 设置请求头
    if (!config.headers["content-type"]) {
      // 如果没有设置请求头
      if (config.method === "post") {
        config.headers["content-type"] = "application/x-www-form-urlencoded"; // post 请求
        config.data = qs.stringify(config.data); // 序列化,比如表单数据
      } else {
        config.headers["content-type"] = "application/json"; // 默认类型
      }
    }
    return config;
  },
  (err: any) => {
    Promise.reject(err);
  }
);
// 此处any 定义统一返回类型 data类型
instance.interceptors.response.use(
  (res: AxiosResponse<BaseResponse<any>>) => {
    if (res.data.code !== 200) {
      message.error(res.data.message);
      throw new Error(res.data.message);
    }
    return res.data.data;
  },
  (err) => {
    Promise.reject(err);
  }
);
export default instance;
